package com.lifang.imsoa.controller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lifang.imsoa.dao.miles.read.FytUserReadMapper;
import com.lifang.imsoa.dao.miles.read.LfEmployeeReadMapper;
import com.lifang.imsoa.entity.miles.FytUser;
import com.lifang.imsoa.entity.miles.LfEmployee;
import com.lifang.imsoa.facade.ImUserFacadeService;
import com.lifang.imsoa.im.service.EasemobChatMessage;
import com.lifang.imsoa.im.service.MessageServiceImpl;
import com.lifang.imsoa.model.BatchDeleteUserResponse;
import com.lifang.imsoa.model.UserBaseResponse;
import com.lifang.imsoa.model.request.AppNameEnum;
import com.lifang.imsoa.model.request.ImUserRequest;
import com.lifang.imsoa.util.DateUtils;
import com.lifang.model.Response;



@Controller
public class TestController {
	Logger logger = LoggerFactory.getLogger(TestController.class);
	@Autowired
	private FytUserReadMapper fytUserReadMapper;
	@Autowired
	ImUserFacadeService imUserFacadeService;
	@Autowired
	LfEmployeeReadMapper lfEmployeeReadMapper;
	@Autowired
	private EasemobChatMessage easemobChatMessage;
	
	@RequestMapping("/getChatMsg.rest")
	@ResponseBody
	public Object getChatMsg(){
		Date start = DateUtils.getDateBySetNo(2015, 11, 15, 10, 25, 4);
		Date end = DateUtils.getDateBySetNo(2015, 11, 19, 10, 25, 29);
		easemobChatMessage.getChatMsg(start,end,false);
		return "success";
//		return demoService.add(15, 14);
	}
	
	@RequestMapping("/registerOne.rest")
	@ResponseBody
	public Object registerOne(){
		logger.info("===>请求来");
		String userId = "yhusotest1";
		ImUserRequest imUserRequest = new ImUserRequest();
		imUserRequest.setUserName("test1");
		imUserRequest.setPassword("123456");
		imUserRequest.setNickName("hehehaha");
//		return imUserFacadeService.xCreateNewIMUserSingle(imUserRequest);
		
			return imUserFacadeService.xCreateNewIMUserSingleForSys("test1", AppNameEnum.WKZF);
//			imUserFacadeService.xDeleteIMUserByUserPrimaryKey("yhusotest1", AppNameEnum.YFYK);
	}
	
	@RequestMapping("/deleteOne.rest")
	@ResponseBody
	public Object deleteOne(){
		logger.info("===>请求来");
		String userId = "yhusotest1";
		try{
			return imUserFacadeService.xDeleteIMUserByUserPrimaryKey(userId,AppNameEnum.YFYK);
		}catch(RuntimeException e){
			System.out.println(e.getMessage());
			return e.getMessage();
		}
	}
	
	//843 76 切面26行
	@RequestMapping("/register.rest")
	@ResponseBody
	public Object register(){
		logger.info("===>请求来");
		int sum = lfEmployeeReadMapper.selectListByPagesCount();//需要注册的总数量
		int sumLimit = 0;//总页数
		if(sum%50==0){
			sumLimit = sum/50;
		}else{
			sumLimit = sum/50+1;
		}
		int registry = 0;//总注册个数
		Long sumMillSec = 0l;//注册总耗时
		List<Response> exCount = new ArrayList<Response>();
		List<Response> errorCount = new ArrayList<Response>();
		for(int i=1;i<=sumLimit;i++){
			Map<String,Object> param = new HashMap<String, Object>();
			getParamByPage(param, i, 50);
			List<LfEmployee> users = lfEmployeeReadMapper.selectListByPages(param);
			List<String> imUsers = new ArrayList<String>();
			for(LfEmployee user:users){
				imUsers.add(user.getId()+"");
			}
			long oneTimeStartTime = System.currentTimeMillis();
			Response<?> registerResult = imUserFacadeService.xCreateNewIMUserBatchGen(imUsers,AppNameEnum.YFYK);
			int sucCountPerTime = 0;//每次成功个数
			if(registerResult.getStatus()==1){
				UserBaseResponse ubr = (UserBaseResponse)registerResult.getData();
				sucCountPerTime = ubr.getEntities().size();
			}else{
				if("用户名已存在".equals(registerResult.getMessage())){
					for(LfEmployee user:users){
						Response<?> singleRes = imUserFacadeService.xCreateNewIMUserSingleForSys(user.getId()+"", AppNameEnum.YFYK);
						if(singleRes.getStatus()==1){
							sucCountPerTime += 1;
						}else{
							errorCount.add(singleRes);
							if(!"用户名已存在".equals(singleRes.getMessage())){
								logger.info("单个注册异常情况={}",singleRes.getMessage());
							}
						}
					}
				}else{
					exCount.add(registerResult);
					logger.info("总异常情况={}",registerResult);
				}
						
			}
			Long oneTimeMillSec = System.currentTimeMillis()-oneTimeStartTime;
			Long oneTimeSecond = oneTimeMillSec/1000;
			logger.info("第{}页成功注册个数={},耗时={}秒,{}毫秒",i,sucCountPerTime, 
					oneTimeSecond.intValue(), oneTimeMillSec);
			//统计总成功个数和总时间
			registry += sucCountPerTime;
			sumMillSec += oneTimeMillSec;
		}
		Long sumSec = sumMillSec/1000;
		logger.info("注册账户总个数={},耗时={}秒,{}毫秒",registry,sumSec.intValue(), sumMillSec);
		
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("regSum", registry);
		result.put("sumSec", sumSec.intValue());
		result.put("sumMillSec", sumMillSec);
		result.put("errorCount", errorCount.size());
		result.put("exCount", exCount.size());
		return result;
	}
	
	public Map<String,Object> regLast(){
		List<FytUser> users = fytUserReadMapper.selectLastPage();
		ImUserRequest imUserRequest = new ImUserRequest();
		logger.info("最后一页总个数={}",users.size());
		int correctNum = 0;
		int errorNum = 0;
		for(FytUser user:users){
			imUserRequest.setUserName("jrsp"+user.getId());
			imUserRequest.setPassword("123456");
			imUserRequest.setNickName(user.getUserName());
			try{
				UserBaseResponse ubr = imUserFacadeService.xCreateNewIMUserSingle(imUserRequest);
				logger.info("注册成功,userId={},ubr={}",user.getId(),ubr.toString());
				correctNum += 1;
			}catch(Exception e){
				errorNum += 1;
				logger.info("注册错误,userId={}",user.getId(),e);
			}
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("correctNum", correctNum);
		map.put("errorNum", errorNum);
		return map;
	}
	
	@RequestMapping("/delete.rest")
	@ResponseBody
	public Object delete(){
		logger.info("===>请求来");
		int sum = fytUserReadMapper.selectListByPagesCount();
		logger.info("用户总量={}",sum);
		int delCount = 0;
		long sumStartTime = System.currentTimeMillis();
		for(int i=1;i<=sum/300+1;i++){
			long startTime = System.currentTimeMillis();
			BatchDeleteUserResponse bdur = null;
//			bdur =imUserFacadeService.xDeleteIMUserByUsernameBatch((long)300, null);
			Long millSec = System.currentTimeMillis()-startTime;
			Long second = millSec/1000;
			logger.info("删除账户个数={},耗时={}秒,{}毫秒",bdur.getEntities().size(),second.intValue(),millSec);
			delCount += bdur.getEntities().size();
		}
		Long sumMillSecond = System.currentTimeMillis()-sumStartTime;
		Long sumSecond = sumMillSecond/1000;
		logger.info("删除账户个数={},耗时={}秒,{}毫秒",delCount,sumSecond.intValue(),sumMillSecond);
		return delCount;
	}
	
	public static void getParamByPage(Map<String,Object> param,int page,int rowPer){
		param.put("start", (page-1)*rowPer);
		param.put("end", rowPer);
	}
	
	public static void main(String[] args) {
//		String a = "/registerOne.rest";
//		String a = "/delete.rest";
//		String a = "/deleteOne.rest";
//		String a = "/register.rest";
		String a = "/getChatMsg.rest";
		try {
			String result = IOUtils.toString(new URL("http://127.0.0.1:8080"+a));
			System.out.println("<====="+result);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Map<String,Object> registerJrsp(){
		int sum = fytUserReadMapper.selectListByPagesCount();
		int registry = 0;
		Long sumMillSec = 0l;
		int sumLimit = 0;
		if(sum%50==0){
			sumLimit = sum/50;
		}else{
			sumLimit = sum/50+1;
		}
		for(int i=1;i<=sumLimit;i++){
			Map<String,Object> param = new HashMap<String, Object>();
			getParamByPage(param, i, 50);
			List<FytUser> users = fytUserReadMapper.selectListByPages(param);
			List<String> imUsers = new ArrayList<String>();
			for(FytUser user:users){
				imUsers.add(user.getId()+"");
			}
			long startTime = System.currentTimeMillis();
			imUserFacadeService.xCreateNewIMUserBatchGen(imUsers,AppNameEnum.JRSP);
			Long millSec = System.currentTimeMillis()-startTime;
			Long second = millSec/1000;
//			logger.info("注册账户个数={},分页参数start={},end={},耗时={}秒,{}毫秒",ubr.getEntities().size(),
//					param.get("start"),param.get("end"),second.intValue(),millSec);
//			sumMillSec += millSec;
//			registry += ubr.getEntities().size();
		}
		Long sumSec = sumMillSec/1000;
		logger.info("注册账户总个数={},耗时={}秒,{}毫秒",registry,sumSec.intValue(), sumMillSec);
		Map<String,Object> lastResult = regLast();
		
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("regSum", registry);
		result.put("sumSec", sumSec.intValue());
		result.put("sumMillSec", sumMillSec);
		result.put("correctNum", lastResult.get("correctNum"));
		result.put("errorNum", lastResult.get("errorNum"));
		int sumRegNum = registry+Integer.parseInt(lastResult.get("correctNum").toString())+
				Integer.parseInt(lastResult.get("errorNum").toString());
		result.put("sumRegNum", sumRegNum);
		return result;
	}
	
}
